import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Form, Input, Select, Avatar, Button, Upload, Icon, message,Checkbox } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import api from "../../../api/api";
import axios from 'axios';
const { Option } = Select;
const FormItem = Form.Item;


function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('请选择png或者jpg图片');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2M');
  }
  return isJpgOrPng && isLt2M;
}

@Form.create()
class Model extends React.Component {

  formRef = React.createRef()
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      hiddenFlag:true,
      visible: false,
      logoImageUrl: '',
      intervalObj: Object,
      intervalCount: 0,
      param: {
        id: "",
        uinfoName:"",
        uinfoGender: "",
        uinfoPhone:"",
        uinfoEmail:"",
        userinfoIdcard: "",
        belongAreaId: "",
      }
    };
  }
  componentDidMount() {
    this.clearData()
    this.props.onRef(this)
  }
  componentWillUnmount(){
    clearInterval(this.state.intervalObj)
  }
//确定
  handleOk = () => {
    this.props.form.validateFields((error, values) => {
      console.info("values=========", values);
      console.info(values.uinfoEmail);
      if (error != null) {
        return;
       }else{
         const that = this;
           let {param} = this.state
            param.uinfoName = values.uinfoName
            param.uinfoGender = values.uinfoGender
            param.uinfoPhone = values.uinfoPhone
            param.uinfoIdcard = values.uinfoIdcard
            param.uinfoEmail = values.uinfoEmail
            param.belongAreaId = values.belongAreaId
            this.setState({param}, () => {
              this.personData()
            })
      }
    })
  }

  //添加，编辑请求提交
  personData() {
    console.log(this.state.param)
    let url = ""
    if(this.props.data.type === 2) {  //编辑
      url = api.api_URL + "/employee/updateUserInfoById"
      let { param } = this.state
      param.id = this.props.data.gridList.id
      this.setState({ param }, () => {
        this.addUser(url)
      })
    }else {                         //添加
      url = api.api_URL + "/employee/insertUserInfo"
      if(this.props.data.type === 1) {
        this.addUser(url)
      }
    }
  }


  //初始化编辑数据
  initEditData = () => {
    let that = this;
       that.setBaseInfo()
  }
  //编辑的初始值设置
  setBaseInfo(){
    let that = this;
    let data = this.props.data.gridList
    console.log(data)

    const { form } = this.props;
      Object.keys(form.getFieldsValue()).forEach(key => {
        const obj = {};
        if (data[key]) {
          obj[key] = data[key] || null;
        }
        form.setFieldsValue(obj);
      });


  }
  //添加
  addUser(url){
    const that = this;
    console.log(this.state.param)
    axios({
      method: 'POST',
      url: url,
      data: JSON.stringify(this.state.param),
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": "application/json;charset=UTF-8"
      },
    }).then(function (res) {
      that.handleCancel()
      console.log(res)
      if(res.data.errorCode!=1){
        message.error({content:"失败！"})
        return;
      }
      message.success({content:"成功！"})
    }).catch(function (error) {
      message.error({content:"失败！"})
      console.log(error);
     })
  }
  handleCancel = e => {
    this.clearData()
    this.props.handleCancel()
  };


  //清空form表单数据
  clearData() {
    this.props.form.resetFields();
    this.setState({
      // uinfoName:"",
      // uinfoGender:"",
      // uinfoPhone:"",
      // uinfoEmail:"",
      // userinfoId:"",
      belongAreaId: undefined,
    })
  }


  render() {
    const { getFieldDecorator, getFieldError } = this.props.form
    const { logoImageUrl } = this.state;
    const CheckboxGroup = Checkbox.Group;
    const uploadButton = (
        <div>
          {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div className="ant-upload-text">上传头像</div>
        </div>
    );
    return (
      <div>
        <Modal
          title={this.props.data.title}
          visible={this.props.data.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form name="control-ref"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            layout="horizontal"
          >
            <FormItem  label="姓名" name="uinfoName" >
              {getFieldDecorator("uinfoName", {})(
                  <Input/>
              )}
            </FormItem>
            <FormItem label="性别"  name="uinfoGender">
              {getFieldDecorator("uinfoGender", {
                initialValue: "男"
              })(
                    <Select>
                    <Option key="男">男</Option>
                    <Option key="女">女</Option>
                  </Select>
              )}

            </FormItem>
            <FormItem   label="手机号" name="uinfoPhone" >
              {getFieldDecorator("uinfoPhone", {
              rules: [{ required: true, message: '请填写客户电话!',whitespace: true,}] ,
              })(
                  <Input />
              )}
            </FormItem>

            <FormItem  label="身份证" name="uinfoIdcard">
              {getFieldDecorator("uinfoIdcard",  {
                rules: [{ required: true, message: '请填写身份证!',whitespace: true,}] ,
              })(
                  <Input />
              )}
            </FormItem>

            <FormItem  label="邮箱" name="uinfoEmail">
              {getFieldDecorator("uinfoEmail",  {
                rules: [{ required: true, message: '请填写邮箱!',whitespace: true,}] ,
              })(
                  <Input />
              )}
            </FormItem>
            <FormItem  label="所属区域" name="belongAreaId">
              {getFieldDecorator("belongAreaId",  {
                initialValue: "1"
              })(
                  <Select>
                    <Option key="1">天津和平区</Option>
                    <Option key="2">天津南开区</Option>
                  </Select>
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
Model.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}
export default Model
